package com.kingway.effect;


import com.kingway.effect.R;

import android.app.Activity;
import android.graphics.Bitmap;
import android.graphics.BitmapFactory;
import android.graphics.Canvas;
import android.graphics.LinearGradient;
import android.graphics.Matrix;
import android.graphics.Paint;
import android.graphics.PorterDuffXfermode;
import android.graphics.Bitmap.Config;
import android.graphics.PorterDuff.Mode;
import android.graphics.Shader.TileMode;
import android.os.Bundle;
import android.widget.ImageView;

public class ReflectedImageAcivity extends Activity {
	private ImageView image;
	
	@Override
	public void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.reflection);
		image = (ImageView) findViewById(R.id.img);
		image.setImageBitmap(createReflectedImages(4, 1));
	}

	public Bitmap createReflectedImages(int total, int weight) {
		final int reflectionGap = -1; //the gap between origin and reflection 
		Bitmap originalImage = BitmapFactory.decodeResource(this.getResources(), R.drawable.test);
		int width = originalImage.getWidth();
		int height = originalImage.getHeight();
		int cut = total - weight;
		int unitHeight = height / total;
		Matrix matrix = new Matrix();
		matrix.preScale(1, -1);
		Bitmap reflectionImage = Bitmap.createBitmap(originalImage, 0, unitHeight * cut, width, unitHeight * weight, matrix, false);
		Bitmap bitmapWithReflection = Bitmap.createBitmap(width, (height + reflectionImage.getHeight()), Config.ARGB_8888);
		Canvas canvas = new Canvas(bitmapWithReflection);
		//draw origin image
		canvas.drawBitmap(originalImage, 0, 0, null);
		//draw reflection image
		canvas.drawBitmap(reflectionImage, 0, height + reflectionGap, null);
		//create a shader that draws a linear gradient along a line.
		Paint paint = new Paint();
		LinearGradient shader = new LinearGradient(0, height, 0, bitmapWithReflection.getHeight() + reflectionGap, 0x70ffffff, 0x00ffffff, TileMode.MIRROR);
		paint.setShader(shader);
		paint.setXfermode(new PorterDuffXfermode(Mode.DST_IN));
		//make shader come into effect
		canvas.drawRect(0, height, width, bitmapWithReflection.getHeight() + reflectionGap, paint);
		//free up the memory 
		originalImage.recycle();
		reflectionImage.recycle();
		return bitmapWithReflection;
	}
}